package com.jagochan.module.rbac.sys_role.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jagochan.module.rbac.sys_role.domain.SysRole;
import com.jagochan.module.rbac.sys_role.mapper.SysRoleMapper;
import com.jagochan.module.rbac.sys_role.service.SysRoleService;
import com.jagochan.module.rbac.sys_role_menu.domain.SysRoleMenu;
import com.jagochan.module.rbac.sys_role_menu.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMenuService sysRoleMenuService;

    /**
     * 给角色分配菜单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean assignMenuForRole(String roleId, List<Long> menuList) {
        if (menuList == null || menuList.isEmpty() || StringUtils.isEmpty(roleId)) return false;

        // 根据角色ID删除
        boolean removeOk = sysRoleMenuService.removeByRoleId(roleId);

        List<SysRoleMenu> roleMenuList = menuList.stream().map(menuId -> SysRoleMenu.builder()
                .menuId(menuId).roleId(Long.valueOf(roleId))
                .build()).collect(Collectors.toList());
        return sysRoleMenuService.saveBatch(roleMenuList);
    }
}